package com.guapi.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.guapi.annotation.SelfController;
import com.guapi.dao.ResponseData;
import com.guapi.dao.User;
import com.guapi.exception.SelfException;
import com.guapi.service.UserService;
import com.guapi.util.RedisUtil;
import com.guapi.util.request.SelfRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 瓜皮哦
 */
@SelfController
@RequestMapping("/user")
@ResponseBody
public class UserController extends BaseController<User> {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/list")
    public ResponseData getUserList(HttpServletRequest request, @RequestBody Map data) {
        User loginUser = getLoginUser();
        System.out.println("loginUser——————:" + loginUser);
        startPage(data);
        List<User> allUserList;
        Map searchStr = (Map) data.get("searchStr");
        String account = "";
        String name = "";
        if (searchStr != null) {
            account = (String) searchStr.get("account");
            name = (String) searchStr.get("name");
        }
        User user = new User();
        if (StrUtil.isAllEmpty(account, name)) {
            allUserList = userService.list();
        } else {
            if (StrUtil.isNotEmpty(account)) {
                user.setAccount(account);
            }
            if (StrUtil.isNotEmpty(name)) {
                user.setUsername(name);
            }
            allUserList = userService.getByFuzzy(user);
        }

        responseData.setRows(allUserList);
        responseData.setSuccess(true);
        return responseData;
    }

    @RequestMapping("/add/{judgeEdit}")
    public ResponseData addUser(HttpServletRequest request, @RequestBody User user, @PathVariable("judgeEdit") boolean judgeEdit) {
        User loginUser = getLoginUser();
        SelfRequest selfRequest = createRequest(request);
        if (judgeEdit) {
            user.setUpdateBy(String.valueOf(loginUser.getId()));
        } else {
            user.setCreateBy(String.valueOf(loginUser.getId()));
        }
        responseData = new ResponseData();
        User dbUser = userService.saveUser(user, judgeEdit);
        if (ObjectUtil.equal(dbUser, user)) {
            responseData.setData("user", user);
            responseData.setSuccess(true);
        } else {
            throw new SelfException("401", "当前用户已存在,请检查账号或邮箱信息是否重复");
        }
        return responseData;
    }

    @RequestMapping("/delete")
    public ResponseData deleteUser(HttpServletRequest request, @RequestBody User user) {
        SelfRequest selfRequest = createRequest(request);
        User loginUser = getLoginUser();
        System.out.println("loginUser——————:" + loginUser);
        user.setUpdateBy(String.valueOf(loginUser.getId()));
        responseData = new ResponseData();
        if (userService.deleteById(user).equals(user)) {
            responseData.setSuccess(true);
            responseData.setData("user", user);
        }
        return responseData;
    }

    /**
     * 头像上传
     *
     * @param request
     * @param file
     * @return
     */
    @RequestMapping("/header/upload")
    public ResponseData uploadHeader(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        responseData = new ResponseData();
        User loginUser = getLoginUser();
        try {
            String[] split = file.getResource().getFilename().split("\\.");
            String type = split[split.length - 1];
            InputStream is = file.getInputStream();
            byte[] bytes = file.getBytes();
            redisTemplate.opsForValue().set(RedisUtil.getUserHeaderKey(String.valueOf(loginUser.getId())), bytes);
            String userHeader = getUserHeader(loginUser) + "." + type;
            loginUser.setHeaderUrl(userHeader);
            FileUtil.writeFromStream(is, resourcePath + "\\" + userHeader);
            if (userService.saveOrUpdate(loginUser)) {
                responseData.setData("user", loginUser);
                responseData.setSuccess(true);
            }
            return responseData;
        } catch (IOException e) {
            e.printStackTrace();
            throw new SelfException("文件读取异常，请稍后重试");
        }
    }

    @RequestMapping("/header/delete")
    public ResponseData uploadHeader(HttpServletRequest request) {
        responseData = new ResponseData();
        User loginUser = getLoginUser();
        loginUser.setHeaderUrl(NULL);

        String userHeader = getUserHeader(loginUser);
        File folder = new File(resourcePath + "\\" + userHeader).getParentFile();
        String regex = "^.*" + Pattern.quote(userHeader) + "\\.(jpg|jpeg|png|gif|bmp)$";
        Pattern pattern = Pattern.compile(regex);
        boolean success = false;

        if (folder.exists() && folder.isDirectory()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isFile()) {
                        String fileName = file.getName();
                        Matcher matcher = pattern.matcher(file.getAbsolutePath());
                        if (matcher.matches()) {
                            success = FileUtil.del(file);
                        }
                    }
                }
            }
        }
        if (userService.saveOrUpdate(loginUser)) {
            redisTemplate.delete(RedisUtil.getUserHeaderKey(String.valueOf(loginUser.getId())));
            responseData.setSuccess(success);
            responseData.setData("user", loginUser);
        }
        return responseData;
    }

    /**
     * 通过Id获取用户数据
     *
     * @param request
     * @param users
     * @return
     */
    @RequestMapping("/detail")
    public ResponseData getUserDetailById(HttpServletRequest request, @RequestBody List<User> users) {
        responseData = new ResponseData();
        ArrayList<User> userList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(users)) {
            for (User user : users) {
                if (ObjectUtil.isNotNull(user)) {
                    userList.add(userService.getById(user.getId()));
                }
            }
        }
        responseData.setRows(userList);
        responseData.setSuccess(true);
        return responseData;
    }

    @RequestMapping("/hasMail/{judge}")
    public ResponseData getUsersHasMail(HttpServletRequest request, @PathVariable("judge") boolean judge) {
        responseData = new ResponseData();
        responseData.setRows(userService.getUserHasMail(judge));
        responseData.setSuccess(true);
        return responseData;
    }

    @RequestMapping("/listByParams")
    public ResponseData getUsersByParams(HttpServletRequest request, @RequestBody Map data) {
        responseData = new ResponseData();
        startPage(data);
        Map params = (Map) data.get("params");
        User user = BeanUtil.mapToBean(params, User.class, true, null);
        List<User> fuzzyList = userService.getByFuzzy(user);
        responseData.setRows(fuzzyList);
        responseData.setSuccess(true);
        return responseData;
    }

}
